#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: paginate.py
@contact: zwb15083976291@163.com
@time: 2021/10/10
"""
from django.core.paginator import EmptyPage
from rest_framework.pagination import BasePagination


def get_pagenate_template(validated_data, paginator):
    """获取分页返回模板"""
    return dict(pageNum=validated_data.get('pageNum'),
                pageSize=validated_data.get("pageSize"),
                total=paginator.count,
                totalPages=paginator.num_pages
                )


class CommonPaginator(BasePagination):
    """通用试图分页器"""

    def paginate_queryset(self, queryset, params_dict: dict) -> tuple:
        """对查询集进行分页"""
        paginator = queryset.paginate(per_page=params_dict.get('pageSize'))
        try:
            models = paginator.page(number=params_dict.get('pageNum'))
        except EmptyPage as e:
            models = []
        return paginator, models

    def get_paginated_response(self, validated_data: dict, paginator: "paginator obj", serialized_data: list) -> dict:
        """返回含有分页参数的结果"""
        data_template = get_pagenate_template(validated_data, paginator)
        data_template.update(result=serialized_data)
        return data_template


class GenericAPIPaginateMixin(object):
    """通用视图分页拓展"""

    def paginate_queryset(self, queryset, params_dict) -> "paginator, models":
        """
        Return a single page of results, or `None` if pagination is disabled.
        """
        if self.paginator is None:
            return None
        return self.paginator.paginate_queryset(queryset, params_dict)

    def get_paginated_response(self, validated_data: dict, paginator: "paginator obj",
                               serialized_data: list) -> dict:
        """
        Return a paginated style `Response` object for the given output data.
        """
        assert self.paginator is not None
        return self.paginator.get_paginated_response(validated_data, paginator,
                                                     serialized_data)
